# 定义过滤器 转换索引
import functools

from flask import g, session, current_app

from info.models import User


def index_convert(index):
    index_dict = {1: "first", 2: "second", 3: "third"}
    return index_dict.get(index, "")



# 查询登录信息
def user_login_data(f):  # f = news_detail

    @functools.wraps(f)  # 该装饰器可以让闭包使用指定函数的信息(如函数名f.__name__ 函数文档注释f.__doc__)
    def wrapper(*args, **kwargs):
        # 判断用户是否登录  `从session中取userid`
        user_id = session.get("user_id")
        user = None
        if user_id:  # 已登录
            # 根据userid取出用户信息
            try:
                user = User.query.get(user_id)
            except BaseException as e:
                current_app.logger.error(e)

        g.user = user

        return f(*args, **kwargs)

    return wrapper


access_key = "kJ8wVO7lmFGsdvtI5M7eQDEJ1eT3Vrygb4SmR00E"
secret_key = "rGwHyAvnlLK7rU4htRpNYzpuz0OHJKzX2O1LWTNl"
bucket_name = "infonews"  # 存储空间名称


def img_upload(data):
    """
    上传图片
    :param data: 上传的文件
    :return:  生成的文件名
    """
    import qiniu


    q = qiniu.Auth(access_key, secret_key)
    key = None  # 文件名, 如果不设置, 会生成随机文件名
    token = q.upload_token(bucket_name)
    # 上传文件
    ret, info = qiniu.put_data(token, key, data)

    if ret is not None:
        return ret.get("key")  # 获取生成的随机文件名
    else:
        raise BaseException(info)

